<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <div slot="header">
          <span>{{id ? '试题修改' : '试题录入'}}</span>

        </div>
        <div>
          <el-form
            ref="form"
            :model="form"
            :rules="rules"
            label-width="80px"
          >
            <!-- 学科 -->
            <el-form-item
              label="学科:"
              label-width="120px"
              prop="subjectID"
            >
              <el-select
                @focus="hSubjectList"
                @change="hCatalog"
                style="width: 400px"
                v-model="form.subjectID"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in subjectsList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 目录 -->
            <el-form-item
              label="目录:"
              label-width="120px"
              prop="catalogID"
            >
              <el-select
                style="width: 400px"
                v-model="form.catalogID"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in catalog"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 企业 -->
            <el-form-item
              label="企业:"
              label-width="120px"
              prop="enterpriseID"
            >
              <el-select
                style="width: 400px"
                v-model="form.enterpriseID"
                placeholder="请选择"
                @focus="hEntList"
              >
                <el-option
                  v-for="item in enterpriseList"
                  :key="item.id"
                  :label="item.shortName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <!--城市 -->
            <el-form-item
              label="城市:"
              label-width="120px"
              prop="city"
            >
              <el-select
                v-model="form.province"
                style="width:198px"
                placeholder="请选择"
                @focus="getCityData"
                @change="handleProvince"
                value-key="item"
              >
                <el-option
                  v-for="item in provinces"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
              <el-select
                v-model="form.city"
                placeholder="请选择"
                style="width: 198px; margin-left: 4px;"
              >
                <el-option
                  v-for="item in citys"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 方向 -->
            <el-form-item
              label="方向:"
              label-width="120px"
              prop="direction"
            >
              <el-select
                style="width: 400px"
                v-model="form.direction"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in direction"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 题型 -->
            <el-form-item
              label="题型:"
              label-width="120px"
              prop="questionType"
            >
              <el-radio-group v-model="form.questionType">
                <el-radio
                  v-model="form.questionType"
                  label="1"
                >单选</el-radio>
                <el-radio label="2">多选</el-radio>
                <el-radio label="3">简答</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 难度 -->
            <el-form-item
              label="难度:"
              label-width="120px"
              prop="difficulty"
            >
              <el-radio-group v-model="form.difficulty">
                <el-radio
                  v-model="form.difficulty"
                  label="1"
                >简单</el-radio>
                <el-radio label="2">一般</el-radio>
                <el-radio label="3">困难</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 题干 -->
            <el-form-item
              label="题干:"
              label-width="120px"
              prop="question"
            >
              <!-- 富文本编辑器 -->
              <quillEditor
                v-model="form.question"
                :options="editorOption"
                @blur="changeQuestion"
              />
            </el-form-item>
            <!-- 选项 -->
            <div v-if="form.questionType !== '3'">

              <el-form-item
                label="选项:"
                label-width="120px"
              >
                <QuestionType
                  ref="QueType"
                  :questionType="form.questionType"
                />
              </el-form-item>
            </div>
            <!-- 解析视屏 -->
            <el-form-item
              label="解析视频:"
              label-width="120px"
              prop="videoURL"
            >
              <el-input
                v-model="form.videoURL"
                style="width: 400px"
              ></el-input>
            </el-form-item>
            <!-- 答案解析 -->
            <el-form-item
              label="答案解析:"
              label-width="120px"
              prop="answer"
            >
              <!-- 富文本编辑器 -->
              <quillEditor
                ref="answerEditor"
                v-model="form.answer"
                :options="editorOption"
                @blur="changeQuillEditor"
              />
            </el-form-item>
            <!-- 题目备注 -->
            <el-form-item
              label="题目备注:"
              label-width="120px"
              prop="remarks"
            >
              <el-input
                style="width: 400px"
                type="textarea"
                :rows="5"
                v-model="form.remarks"
              >
              </el-input>
            </el-form-item>
            <!-- 试题标签 -->
            <el-form-item
              label="试题标签:"
              label-width="120px"
              prop="tags"
            >
              <el-select
                style="width: 400px"
                v-model="form.tags"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请选择文章标签"
              >
                <el-option
                  v-for="item in tags"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <!-- 按钮 -->
            <el-form-item label-width="120px">
              <el-button type="primary" v-if="!id" @click="onSubmit">确认提交</el-button>
              <el-button type="success" v-else @click="onSubmit">确认修改</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>

    </div>
  </div>
</template>

<script>
import 'highlight.js/styles/monokai-sublime.css'
import hljs from 'highlight.js'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor' // 富文本组件
import { provinces, citys } from '@/api/hmmm/citys.js' // 城市
import { direction } from '@/api/hmmm/constants.js' // 方向
import { simple as subList } from '@/api/hmmm/subjects.js' // 学科
import { simple as cataList } from '@/api/hmmm/directorys.js' // 目录
import { list as entList } from '@/api/hmmm/companys.js' // 企业目录
import { simple as tagList } from '@/api/hmmm/tags.js' // 标签
import { add as addquestion, detail as detquestion, update as updquestion } from '@/api/hmmm/questions.js' // 题库
import QuestionType from './companys/options.vue'
// 工具栏配置
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
  ['blockquote'], // 引用  代码块
  ['code-block', 'image', 'link'] // 链接、图片、视频
]
export default {
  name: 'questionsNew',
  data () {
    return {
      id: this.$route.query.id || null,
      tags: [],
      subjectsList: [], // 学科
      catalog: [], // 目录
      provinces: [], // 地区
      enterpriseList: [], // 企业
      direction, // 方向
      citys: [], // 城市
      editorOption: { // 富文本配置
        placeholder: '',
        modules: {
          toolbar: {
            container: toolbarOptions
          },
          syntax: {
            highlight: text => {
              return hljs.highlightAuto(text).value // 富文本代码高亮
            }
          }
        }
      },
      form: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [], // 选项
        videoURL: '', // 视屏
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: [] // 试题标签
      },
      rules: {
        subjectID: [{ required: true, message: '学科不能为空', trigger: 'change' }],
        catalogID: [{ required: true, message: '目录不能为空', trigger: 'change' }],
        enterpriseID: [{ required: true, message: '企业不能为空', trigger: 'change' }],
        province: [{ required: true, message: '城市不能为空', trigger: 'change' }],
        city: [{ required: true, message: '地区不能为空', trigger: 'change' }],
        direction: [{ required: true, message: '方向不能为空', trigger: 'change' }],
        citquestionTypey: [{ required: true, message: '题型不能为空', trigger: 'change' }],
        difficulty: [{ required: true, message: '难度不能为空', trigger: 'change' }],
        question: [{ required: true, message: '题干不能为空', trigger: 'blur' }],
        answer: [{ required: true, message: '答案解析不能为空', trigger: 'change' }],
        tags: [{ required: true, message: '标签不能为空', trigger: 'change' }],
        videoURL: [{ required: true, message: '解析视频不能为空', trigger: 'change' }],
        remarks: [{ required: true, message: '题目备注不能为空', trigger: 'change' }]
      }
    }
  },
  components: {
    quillEditor,
    QuestionType
  },
  created () {
    document.body.scrollTop = 0
    this.id && this.dataBackfill()
  },
  mounted () {
    this.$refs.answerEditor.quill.enable(false)
    setTimeout(() => {
      this.$refs.answerEditor.quill.enable(true)
    }, 1000)
  },
  methods: {
    // 获取标签
    // 数据回填
    async dataBackfill () {
      try {
        const res = await detquestion({ id: this.id })
        await this.hSubjectList()
        this.hEntList()
        // 学科
        this.form = res.data
        // 标签
        this.form.tags = res.data.tags.split(',')
        await this.hCatalog()
        console.log(this.form.options)
        this.xxOptions(this.form.options)
      } catch (err) {
        console.log(err)
      }
    },
    // 选项数据转换
    xxOptions (options) {
      console.log(options)
      // 选项
      options.map(item => {
        item.isRight
          ? item.isRight = true
          : item.isRight = false
      })
      this.$refs.QueType.options = options.sort(this.opSort('code'))

      if (this.form.questionType === '1') {
        if (options.filter(item => item.isRight).length) this.$refs.QueType.isRight = options.filter(item => item.isRight)[0].code
      } else if (this.form.questionType === '2') {
        this.$refs.QueType.isRight = options.reduce((a, c) => {
          if (c.isRight) {
            return [...a, c.code]
          }
          return a
        }, [])
      }
    },
    // 排序
    opSort (keyName) {
      return function (objectN, objectM) {
        var valueN = objectN[keyName]
        var valueM = objectM[keyName]
        if (valueN < valueM) return -1
        else if (valueN > valueM) return 1
        else return 0
      }
    },
    // 富文本渲染
    changeQuillEditor () {
      this.$refs.form.validateField('answer')
    },
    // 富文本渲染
    changeQuestion () {
      this.$refs.form.validateField('question')
    },
    // 添加题
    async onSubmit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.id ? this.daUpd() : this.doAdd()
        } else {
          this.$message.error('表单不能为空')
          console.log('error submit!!')
          return false
        }
      })
      console.log('submit!')
    },
    // 重置表单
    doResetForm () {
      this.form = {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [], // 选项
        videoURL: '', // 视屏
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: [] // 试题标签
      }
    },
    // 添加
    async doAdd () {
      try {
        this.form.tags = this.form.tags.join(',')
        this.form.options = this.$refs.QueType.options
        console.log(this.$refs.QueType.options)
        const res = await addquestion({ ...this.form })
        console.log(res)
        this.$message.success('添加成功')
        this.$router.push('/questions/list')
      } catch (err) {
        this.$message.error('添加失败')
        console.log(err)
      } finally {
        this.doResetForm()
      }
    },
    // 修改
    async daUpd () {
      try {
        this.form.tags = this.form.tags.join(',')
        this.form.options = this.$refs.QueType.options
        const res = await updquestion({ ...this.form })
        console.log(res)
        this.$message.success('修改成功')
        this.$router.go(-1)
      } catch (err) {
        this.$message.error('修改失败')
        console.log(err)
      } finally {
        this.doResetForm()
      }
    },
    // 获取学科列表
    async hSubjectList () {
      try {
        const res = await subList()
        console.log(res)
        this.subjectsList = res.data
      } catch (err) {
        console.log(err)
      }
    },
    // 获取目录详情
    async hCatalog () {
      try {
        const res = await cataList({ subjectID: this.form.subjectID })
        const subRes = await tagList({ subjectID: this.form.subjectID })
        console.log(subRes)
        this.catalog = res.data
        if (!this.catalog.length) this.form.catalogID = ''
        this.tags = subRes.data
      } catch (err) {
        console.log(err)
      }
    },
    // 获取企业
    async hEntList () {
      console.log(123)
      try {
        const res = await entList()
        this.enterpriseList = res.data.items
      } catch (err) {
        console.log(err)
      }
    },
    // 获取省
    getCityData: function () {
      this.provinces = provinces()
    },
    // 选省获取到市
    handleProvince: function (e) {
      console.log(e)
      this.citys = citys(e)
      this.form.city = this.citys[0]
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  // 文本域
  .ql-toolbar {
    // height: 50px;
    padding: 0px 8px !important;
  }
  .ql-container {
    height: 200px !important;
  }
  // 选项

  // 上传图片按钮
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  // 上传图片按钮 end
}
::v-deep .ql-editor {
  min-height:200px;
}
</style>
